const Client = require('../../Mongoose/OauthClient')
const uniqueString = require('unique-string')
class OauthClientController {
    constructor() {

    }
    // GET 索引列表
    async index (ctx, next) {
        let clients = await Client.find({ 'user_id': ctx.state.user.id }).sort({'created': -1});
        
        await ctx.render('oauth/clients/index', { clients: clients })
    }
    // GET 创建显示表单
    async create (ctx, next) {
        await ctx.render('oauth/clients/create')        
    }
    //POST 保存创建的数据
    async store (ctx, next) {
        let data = {
            user_id: ctx.state.user.id,
            name: ctx.request.body.name,
            redirect_uri: ctx.request.body.redirect_uri,
            secret: uniqueString(),
        }
        await Client.create(data)
        await ctx.redirect('/oauth/client')
    }
    //GET 显示对应id的内容
    async show (ctx, next) {
        let id = ctx.params.id
        let client = await Client.findOne({'_id': id})
        await ctx.render('oauth/clients/show', { client: client })
    }
    //GET 编辑（显示表单）
    async edit (ctx, next) {
        let id = ctx.params.id
        let client = await Client.findOne({ '_id': id })
        await ctx.render('oauth/clients/edit', { client: client })      
    }
    // PUT/PATCH保存
    async save (ctx, next) {
        let id = ctx.params.id
        let data = {
            name: ctx.request.body.name,
            redirect_uri: ctx.request.body.redirect_uri
        }
        let client = await Client.findByIdAndUpdate({ '_id': id }, { $set: data })
        await ctx.redirect('/oauth/client')        
    }
    /**
     * 删除
     * 
     * @param {any} ctx 
     * @param {any} next 
     * @memberof OauthClientController
     */
    async destroy (ctx, next) {
        let id = ctx.params.id
        let res = await Client.findByIdAndRemove({'_id': id})
        await ctx.redirect('/oauth/client')
    }
}
module.exports = new OauthClientController()